package com.dxt.mqtt.utils;

import com.dxt.service.CacheManager;
import com.dxt.common.AppConstant;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * Title:Server 这是发送消息的服务端
 * Description: 服务器向多个客户端推送主题，即不同客户端可向服务器订阅相同主题
 * @author rao
 */

public class ServerMQTTUtil {
    private MqttClient client;
    private MqttTopic mqttTopic;

    /**
     * 构造函数
     * @throws MqttException
     */
    public ServerMQTTUtil(String topic,String clientId,CacheManager cacheManager) throws MqttException {
        //tcp://MQTT安装的服务器地址:MQTT定义的端口号
        String HOST = cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_MQTT_SERVER_URL);
        // MemoryPersistence设置clientid的保存形式，默认为以内存保存
        client = new MqttClient(HOST, clientId, new MemoryPersistence());
        connect(topic,cacheManager);
    }

    /**
     *  用来连接服务器
     */
    private void connect(String topic,CacheManager cacheManager) {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_MQTT_USER_NAME));
        options.setPassword(cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_MQTT_PASSWORD).toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(Integer.parseInt(cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_MQTT_CONN_TIMEOUT)));
        // 设置会话心跳时间
        options.setKeepAliveInterval(Integer.parseInt(cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_MQTT_KEEP_ALIVE)));
        try {
            client.connect(options);
            mqttTopic = client.getTopic(topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送消息并获取回执
    public void publish(MqttMessage message) throws MqttPersistenceException,
            MqttException, InterruptedException {
        MqttDeliveryToken token = mqttTopic.publish(message);
        token.waitForCompletion();
        System.out.println("message is published completely! "
                + token.isComplete());
        System.out.println("messageId:" + token.getMessageId());
        //token.getResponse();

        if (client.isConnected())
            client.disconnect(10000);
        System.out.println("Disconnected: delivery token \"" + token.hashCode()
                + "\" received: " + token.isComplete());
    }

}
